package com.qf.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *
 * 重复消费  监听器
 * @author lixu
 */
@Component
public class RepeatPurchasesListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "hello")
    public void recerverMessage(Message message, Channel channel,Object msg) throws Exception{
        System.out.println("===防止重复消费==" + msg);
        //String id = (String) message.getMessageProperties().getHeaders().get("spring_request_return_correlation");
        String id = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
        //1:加锁  setnx  是否已经加锁
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(id, 0);
        if(isLock){
            //true: 别人未加锁  我加锁 并设置锁的过期时间  1S   我正在保存订单
            redisTemplate.opsForValue().set(id,0,1, TimeUnit.SECONDS);
            //2:保存订单
            System.out.println("//1:保存订单");
            System.out.println("//2:保存订单详情");
            //3: 保存订单完成
            redisTemplate.opsForValue().set(id,1);
            //4: 正常应答队列
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else{
            //false: 别人已加锁
            //3:获取别人已加锁的值 来判断是否已经完成订单的保存
            Integer value = (Integer) redisTemplate.opsForValue().get(id);
            if("1".equals(value)){
                //订单保存已经完成
                System.out.println("====第二个消费者帮助第一个消费者应答==");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }
        }
    }
}
